import axios from 'axios';
import { useLoginUserStore } from '@/index';
import router from '@/router/index';
const api = axios.create({
  baseURL: import.meta.env.MODE === 'development' ? '/apDev' : '/api',
  timeout: 30000,
  withCredentials: true,
  headers: {}
});
const getImage = axios.create({
  baseURL: import.meta.env.MODE === 'development' ? '/imaDev' : '/imag',
  timeout: 300000,
  withCredentials: true,
  headers: {}
});

// api.defaults.headers.common['Authorization'] = sessionStorage.getItem('token');

api.interceptors.request.use(
  config => {
    if (config && config.headers) {
      const { loginUser } = useLoginUserStore();
      // config.headers.Authorization = sessionStorage.getItem('token');
      config.headers.Authorization = loginUser.token;
    }
    return config;
  },
  error => {
    ElMessage.error(error.toJSON());
    return Promise.reject(error);
  }
);

api.interceptors.response.use(
  response => {
    const contentType = response.headers['content-type'];
    //用于控制文件下载
    if (
      contentType ===
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
    ) {
      console.log('开始下载');
      const dispositionStr = response.headers['content-disposition'];
      if (dispositionStr == null || dispositionStr === '') {
        return response;
      }
      const dispositionArr = dispositionStr.split(';');
      let fileName = decodeURIComponent(dispositionArr[1]);
      fileName = fileName.split('=')[1];
      const blob = new Blob([response.data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = fileName;
      link.click();
      URL.revokeObjectURL(url); //释放内存
    }
    return response;
  },
  error => {
    if (error.status === 403) {
      ElMessage.error(error.toJSON());
    } else if (error.status === 401) {
      ElMessage.error('登录已经超时，为您跳转到登录页面');
      router.push('/login');
    } else {
      ElMessage.error(error.toJSON());
      return Promise.reject(error);
    }
  }
);

getImage.interceptors.request.use(
  config => {
    if (config && config.headers) {
      const { loginUser } = useLoginUserStore();
      // config.headers.Authorization = sessionStorage.getItem('token');
      config.headers.Authorization = loginUser.token;
    }
    return config;
  },
  error => {
    ElMessage.error(error.toJSON());
    return Promise.reject(error);
  }
);

getImage.interceptors.response.use(
  response => {
    const contentType = response.headers['content-type'];
    //用于控制文件下载
    if (
      contentType ===
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
    ) {
      console.log('开始下载');
      const dispositionStr = response.headers['content-disposition'];
      if (dispositionStr == null || dispositionStr === '') {
        return response;
      }
      const dispositionArr = dispositionStr.split(';');
      let fileName = decodeURIComponent(dispositionArr[1]);
      fileName = fileName.split('=')[1];
      const blob = new Blob([response.data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = fileName;
      link.click();
      URL.revokeObjectURL(url); //释放内存
    }
    return response;
  },
  error => {
    if (error.status === 403) {
      ElMessage.error(error.toJSON());
    } else if (error.status === 401) {
      ElMessage.error('登录已经超时，为您跳转到登录页面');
      router.push('/login');
    } else {
      ElMessage.error(error.toJSON());
      return Promise.reject(error);
    }
  }
);

export { api, getImage };
